<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>dataTable服务器模式</title>
    <!-- ui -->
    <!-- <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.css"> -->
    <!-- table  -->
    <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- <link href="//cdn.bootcss.com/datatables/1.10.16/css/dataTables.bootstrap4.css" rel="stylesheet"> -->
    <link href="//cdn.bootcss.com/datatables/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet">
    <!-- datatable tb  -->
    <!-- <link href="https://cdn.bootcss.com/datatables/1.10.16/css/dataTables.foundation.css" rel="stylesheet"> -->
    <!-- table fixed tb  -->
    <!-- <link rel="stylesheet" href="./css/fixedColumns.dataTables.min.css" /> -->
    <style>
        .mytable {
            table-layout: fixed;
        }
        /* 显示排序的bug */
        
        th.mycheck {
            padding-right: 15px !important;
        }
        
        th.mycheck:after,
        th.mycheck::before {
            display: none !important;
        }
        /* 强制隐藏分页设置 */
        
        #tb_wrapper>.row:first-child {
            display: none;
        }
        /*扩展input style*/
        
        .mytd-plus td {
            width: 100%;
        }
        
        .mytd-plus label {
            display: inline-flex;
            width: 100px;
        }
        
        .mytd-plus .form-control {
            display: inline-flex;
            flex: auto;
        }
        
        .mytd-plus ul {
            padding-left: 15px;
            padding-right: 15px;
        }
        
        .mytd-plus li {
            margin-top: 15px;
            padding: 0;
        }
    </style>
</head>

<body>
    <!-- page -->
    <div class="page">
        <section class="panel container">
            <h4>
                Datatables(服务器模式)
            </h4>
            <div class="form-inline">
                <form id="search">
                    <button type="button" data-add class="btn btn-success">新建</button>
                    <button type="button" data-remove class="btn btn-danger">删除</button>
                    <select name="name" class="form-control">
                            <option value="name">名称</option>
                            <option value="content">内容</option>
                        </select>
                    <input type="text" name="value" placeholder="查询" class="form-control">
                    <button type="submit" class="btn btn-info">查询</button>
                </form>
            </div>
            <div>
                <table id="tb" class="table table-striped table-bordered mytable" cellspacing="0" width="100%"></table>
            </div>
        </section>
    </div>
    <!-- page end-->

    <script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <!-- table -->
    <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <!-- <script src="//cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> -->
    <!-- table fixed td -->
    <!-- <script src="./js/dataTables.fixedColumns.min.js"></script> -->
    <script src="https://cdn.bootcss.com/datatables/1.10.16/js/dataTables.bootstrap.min.js"></script>
    <script>
        /**
         *@file 多功能表格 服务器模式
         *?new="新建数据"&remove="删除/引索"&editor="修改数据的内容，row为引索"&search="搜索数据的内容"
         *@author qiu(423822728@qq.com)
         */
        $(function() {
            /**
             *thead th config
             *@param {string} data 对应数据字段名
             *@param {string} defaultContent 内容空时填充
             *@param {string} title  显示列标题
             *@param {string} class td's class
             *@param {boolen}  visible 是否显示
             *@param {boolen} orderable 是否排序
             *@param {function} createdCell(td, cellData, rowData, row, col)  初始化时回调
             */
            var columns = [

                //选择按钮
                {
                    "data": "cleackbox",
                    "class": " text-center mycheck",
                    "title": "<input type='checkbox' class='checkded-all' >",
                    "defaultContent": "<input type='checkbox' class='checkded' >",

                    "width": "50px",
                    "orderable": false,
                }, {
                    "data": "name",
                    "title": "名称",
                    // "orderable": false,
                    "defaultContent": ""
                }, {
                    "data": "content",
                    "title": "内容",
                    // "orderable": false,
                    "defaultContent": ""
                }, {

                    //控制按钮
                    "data": "button",
                    "title": "操作", //标题
                    "class": "td-set",
                    "defaultContent": "</button><button data-look  type='button' class='btn btn-success btn-sm'>修改</button>", //默认内容
                    "orderable": false, //不排序
                    "createdCell": function(td, cellData, rowData, row, col) {
                        /**
                         *查看内容
                         */
                        $(td).find("[data-look]").on("click", function() {
                            var $tr = $(this).parents("tr");
                            tdEdior($tr)
                        })

                    }
                }
            ];
            //请求地址
            var SERVER = "data.php";

            /**
             *table init
             *@param {boolen} serverSide 是否开服务器模式
             *@param {Array} columns 列内容配置
             *@param {string} ajax 服务器地址
             *@param {Object}language 语言设置
             *@param {string}language.info 信息文字
             *@param {Object}language.paginate 分页内容显示
             *@param {string}language.paginate.next 下一页显示
             *@param {string}language.paginate.previous 上一页显示
             *@param {string}language.paginate.processing 翻页等待
             */


            var table = $('#tb').DataTable({
                "serverSide": true,
                "columns": columns, //列头
                'ajax': SERVER,
                //重绘时执行
                "drawCallback": function(td, cellData, rowData, row, col) {
                    $(".mytd-plus").remove();
                    $(".checkded-all").prop("checked", false);
                    //全部选择
                    $(".checkded-all").on('change', function() {
                        var bool = $(this).prop("checked");
                        $(".checkded").prop("checked", bool);
                    })
                },
                "language": {
                    "info": "总共_PAGES_页，现_PAGE_页",
                    "paginate": {
                        "next": "下一页",
                        "previous": "上一页",
                        "processing": "正在处理中。。。",
                    }
                },
            });

            /**
             *新建数据
             *
             */
            $("[data-add]").on("click", function() {
                    var $o = $("tr").eq(0);
                    tdEdior($o)

                })
                /**
                 *按name查询
                 *@event search#submit
                 */
            $("#search").on("submit", tdSearch);

            function tdSearch(e) {
                e.preventDefault();
                var data = tdForm($(this));
                tdServer('search', data);
            }

            /**
             *修改查看内容
             * @param {Node} $o 行对象
             */

            function tdEdior($o) {
                //table data
                var data = table.row($o).data();
                // 当前引索
                var row = table.row($o).index();
                //是否已经展开
                if ($o.next().hasClass("mytd-plus")) {

                    $o.next().find("[data-close]").trigger("click");
                    return;
                };
                // 生成展示
                var dom = "<ul class=\"list-unstyled  \">" +
                    "<form class='row'>" +
                    nodeLi('name', "名称", "请输入名称") +
                    nodeLi('content', "内容", "请输入内容") +
                    "<li class='text-right col-xs-12 myform-nav'><button  type='submit' class=\"btn btn-success \" >提交</button><button data-close  type='button' class=\"btn\">取消</button></li>" +
                    "<input type='hidden'name='row' value='" + row + "' >"
                "</form>"
                "</ul>";

                //append tr of html
                $o.after("<tr class='mytd-plus'><td colspan='100'>" + dom + "</td></tr>")

                $obj = $o;
                //提交表单
                var $next = $o.next();
                $next.find("form").on("submit", function(e) {
                    e.preventDefault();
                    var data = tdForm($(this));
                    if (row === undefined) {
                        // 新建
                        tdServer("new", data)
                    } else {
                        //修改
                        tdServer("editor", data)
                    }
                })
                $next.find("[data-close]").on("click", tdPlusColse);
                /**
                 *node li 
                 *@param {string} name 字段名
                 *@param {string} title 标题名
                 *@param {string} pl 站位
                 *@param {stirng} type 输入框属性
                 */
                function nodeLi(name, title, pl, type) {

                    return ("<li class=\"col-md-6  \">" +
                        "     <label>" + title + "</label>" +
                        "       <input type=\"" + (type ? type : 'text') + "\" name=\"" + name + "\" class=\"form-control\" placeholder='" + pl + "' value='" + (data && data[name] ? data[name] : '') + "' >" +
                        "  </li>");
                }
            }
            /**
             *关闭添加修改
             */
            function tdPlusColse() {
                var $o = $(this).parents('tr');
                var data = tdForm($o.find("form"));
                //对比数据是否修改
                var bool = true;
                if (data.row != 'undefined') {
                    //修改
                    var oldData = table.row(data.row).data();
                    for (var k in data) {
                        if (k != 'row') {
                            //内容不一样
                            if (data[k] != oldData[k]) {
                                if (!confirm("内容变更，是否继续关闭")) {
                                    bool = false;
                                }
                                break;
                            };
                        }
                    }

                } else {
                    //新建存在内容时
                    if (!confirm("内容变更，是否继续关闭")) {
                        bool = false;
                    }
                }

                if (bool) $(this).parents('tr').remove();
            }

            /**
             *获得多选数据的引索
             */
            $("[data-remove]").on("click", tdGetChecked)

            function tdGetChecked() {
                //要删除的对象
                var data = [];
                //获得引索
                $("input:checked.checkded ").each(function() {
                    var $tr = $(this).parents("tr");
                    //tr 是通过 data-dt-row 或 num 获得
                    data.push(table.row($tr).index());
                })

                if (data.length) tdServer("deleta", data);
            }
            /**
             *获得表单的数据
             *@param {node} 表单对象
             *@param {$o} 修得的tr对象
             */
            function tdForm($form) {
                var data = {};
                //添加数据
                $form.find("input,textarea,select").each(function() {
                    var $that = $(this);
                    var k = $that.attr("name");
                    var val = $that.val();

                    if (val) {
                        data[k] = val;
                    }
                })
                return data;

            }

            /**
             *get server data 
             *@param {string} type 操作属性
             *@param {Array} data 传参
             */
            function tdServer(type, data) {

                table.ajax.url(SERVER + "?" + type + "=" + JSON.stringify(data)).load();
            }


        })
    </script>
</body>


</html>